package com.consumer.demo2.util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayInputStream;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

public class ResponseUtil {
	
	public static void response(PrintWriter out, Map<String, Object> param)
	{
		try
		{
			out.write(JSON.toJSONString(param, SerializerFeature.WriteMapNullValue));
		}
		catch (Exception e)
		{
			e.printStackTrace();
		}
	}

	public static void responseCode(PrintWriter out, int code)
	{
		Map<String, Object> param = new HashMap<>(1);
		param.put("code", code);
		try {
			out.write(JSON.toJSONString(param, SerializerFeature.WriteMapNullValue));
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	public static void response(HttpServletResponse out, Map<String, Object> param)
	{
		try
		{
			response(out.getWriter(), param);
		}
		catch (Exception e)
		{
			e.printStackTrace();
		}
	}

	
	public static void responseHtml(PrintWriter out, String html)
	{
		try
		{
			out.write(html);
		}
		catch (Exception e)
		{
			e.printStackTrace();
		}
	}
	
	public static void responsePicture(HttpServletResponse out, byte[] picture)
	{
		try
		{
			ImageIO.write(ImageIO.read(new ByteArrayInputStream(picture)), "jpg", out.getOutputStream());
		}
		catch(Exception e)
		{
			e.printStackTrace();
		}
	}
	
}
